package com.aduerr.v1shouyin.mvp.activity;

import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.OrderGetPosOrderLEntity;
import com.aduerr.v1shouyin.entity.ReceivablesDataEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.adpter.OrderRecordAdapter;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.TextUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2018/10/19 17:37
 * @change
 * @chang time
 * @class describe
 */

public class ScanOrderActivity extends AppCompatActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_wx)
    TextView tvWx;
    @BindView(R.id.tv_wx_money)
    TextView tvWxMoney;
    @BindView(R.id.tv_zfb)
    TextView tvZfb;
    @BindView(R.id.tv_zfb_money)
    TextView tvZfbMoney;
    @BindView(R.id.tv_ysf)
    TextView tvYsf;
    @BindView(R.id.tv_ysf_money)
    TextView tvYsfMoney;

    @BindView(R.id.tv_digital)
    TextView tvDigital;
    @BindView(R.id.tv_digital_money)
    TextView tvDigitalMoney;
    @BindView(R.id.v_digital)
    View vDigital;


    @BindView(R.id.tv_tomorrow)
    TextView tvTomorrow;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.v_wx)
    View vWx;
    @BindView(R.id.v_zfb)
    View vZfb;
    @BindView(R.id.v_ysf)
    View vYsf;
    @BindView(R.id.rl_no_data)
    RelativeLayout rlNoData;

    private int mYear, mMonth, mDay;
    private Calendar ca;
    private SimpleDateFormat sDateFormat;
    private int paytype = 1; //1:微信，2：支付宝， 7：云闪付
    private int page = 1;
    private OrderRecordAdapter orderRecordAdapter;
    private Drawable ivArrowGrey;
    private Drawable ivArrowWhite;
    /**
     * 日期选择器对话框监听
     */
    private DatePickerDialog.OnDateSetListener onDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            String days;
            if(mMonth + 1 < 10) {
                if(mDay < 10) {
                    days = new StringBuffer().append(mYear).append("-").append("0").
                            append(mMonth + 1).append("-").append("0").append(mDay).toString();
                } else {
                    days = new StringBuffer().append(mYear).append("-").append("0").
                            append(mMonth + 1).append("-").append(mDay).toString();
                }

            } else {
                if(mDay < 10) {
                    days = new StringBuffer().append(mYear).append("-").
                            append(mMonth + 1).append("-").append("0").append(mDay).toString();
                } else {
                    days = new StringBuffer().append(mYear).append("-").
                            append(mMonth + 1).append("-").append(mDay).toString();
                }

            }
            tvDate.setText(days);
            getDayData();
            getData(ScanOrderActivity.this, 1, paytype);
            if(tvDate.getText().toString().equals(sDateFormat.format(System.currentTimeMillis()))) {
                tvTomorrow.setClickable(false);
                tvTomorrow.setCompoundDrawables(null, null, ivArrowGrey, null);
                tvTomorrow.setTextColor(getResources().getColor(R.color.font_value));
            } else {
                tvTomorrow.setClickable(true);
                tvTomorrow.setCompoundDrawables(null, null, ivArrowWhite, null);
                tvTomorrow.setTextColor(getResources().getColor(R.color.white));
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_order);
        ButterKnife.bind(this);
        initView();
        getData(this, 1, 1);
        getDayData();
    }

    void initView() {
        ca = Calendar.getInstance();
        sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);
        ivArrowGrey = getResources().getDrawable(R.drawable.img_arrow_right_g);
        ivArrowWhite = getResources().getDrawable(R.drawable.img_arrow_right_w);
        ivArrowGrey.setBounds(0, 0, ivArrowGrey.getMinimumWidth(),
                ivArrowGrey.getMinimumHeight());
        ivArrowWhite.setBounds(0, 0, ivArrowWhite.getMinimumWidth(),
                ivArrowWhite.getMinimumHeight());
        tvDate.setText(new StringBuffer().append(mYear).append("-").
                append(mMonth + 1).append("-").append(mDay).toString());
        tvTomorrow.setClickable(false);
        tvTomorrow.setCompoundDrawables(null, null, ivArrowGrey, null);
        tvTomorrow.setTextColor(getResources().getColor(R.color.font_value));
        tvTitle.setText("扫码订单");
        recyclerview.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false));
        DividerItemDecoration divider = new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL);
        divider.setDrawable(getResources().getDrawable(R.drawable.divider));
        recyclerview.addItemDecoration(divider);
        refreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getDayData();
                        /*if(paytype == 1) {
                            getData(ScanOrderActivity.this, 1, 1);
                        }else if(paytype == 2) {
                            getData(ScanOrderActivity.this, 1, 2);
                        }*/
                        getData(ScanOrderActivity.this, 1, paytype);
                        refreshlayout.finishRefresh();
                        refreshlayout.setLoadmoreFinished(false);
                    }
                }, 1500);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        /*if(paytype == 1) {
                            getData(ScanOrderActivity.this, page+1, 1);
                        }else if(paytype == 2) {
                            getData(ScanOrderActivity.this, page+1, 2);
                        }*/
                        getData(ScanOrderActivity.this, page + 1, paytype);
                        refreshlayout.finishLoadmore();

                    }
                }, 1500);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        //触发自动刷新
        refreshLayout.autoRefresh();
    }

    void showDatePick(String date) {
        try {
            Date d = sDateFormat.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(d);
            DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                    DatePickerDialog.THEME_DEVICE_DEFAULT_LIGHT, onDateSetListener,
                    calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH));
            datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
            datePickerDialog.show();
        } catch(ParseException e) {
            e.printStackTrace();
        }

    }

    void getDayData() {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("beginTime", tvDate.getText().toString());
        addParams.put("endTime", addDay(tvDate.getText().toString()));
        APIRetrofit.getAPIService().receivablesData(RXRequest.getXingPosParams(addParams, ScanOrderActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ReceivablesDataEntity>() {

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ReceivablesDataEntity receivablesDataEntity) {
                        int success = receivablesDataEntity.getSuccess();
                        if(success == 1) {
                            String alipaymoney =
                                    receivablesDataEntity.getData().getAlipaymoney();
                            String wxmoney = receivablesDataEntity.getData().getWxmoney();
                            String ysfmoney =
                                    receivablesDataEntity.getData().getYsfmoney();
                            String digitalmoney =
                                    receivablesDataEntity.getData().getDcMoney();
                            tvMoney.setText((new BigDecimal(alipaymoney).add(new BigDecimal(wxmoney))).
                                    add(new BigDecimal(ysfmoney)).add(new BigDecimal(digitalmoney)).toString());
                            tvWxMoney.setText("￥" + wxmoney + "/" + receivablesDataEntity.getData().getWxcount());
                            tvZfbMoney.setText("￥" + alipaymoney + "/" + receivablesDataEntity.getData().getAlipaycount());
                            tvYsfMoney.setText("￥" + ysfmoney + "/" + receivablesDataEntity.getData().getYsfcount());
                            tvDigitalMoney.setText("￥" + (digitalmoney == null ? "0": digitalmoney) + "/"
                                    + (receivablesDataEntity.getData().getDcCount() == null ? "0" : receivablesDataEntity.getData().getDcCount()));
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(ScanOrderActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(ScanOrderActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(ScanOrderActivity.this,
                                    BangGuidActivity.class));
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(receivablesDataEntity.getErrMsg());
                            SharedPreferencesUtils.remove(ScanOrderActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(ScanOrderActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(ScanOrderActivity.this,
                                    LoginActivity.class));
                        } else {
                            ToastUtils.showToast(ScanOrderActivity.this,
                                    receivablesDataEntity.getErrMsg() + "");
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(ScanOrderActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(ScanOrderActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(ScanOrderActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 查询列表
     * @param mContext  context
     * @param p        页码
     * @param paytype  订单类型
     */
    void getData(Context mContext, int p, int paytype) {

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("page", p + "");
        addParams.put("beginDate", tvDate.getText().toString());
        addParams.put("endDate", addDay(tvDate.getText().toString()));
        addParams.put("paytype", paytype + "");
        addParams.put("state", "0");
        APIRetrofit.getAPIService().orderGetPosOrderL(RXRequest.getXingPosParams(addParams, mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderGetPosOrderLEntity>() {

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull OrderGetPosOrderLEntity orderGetPosOrderLEntity) {
//                        if (Tools.isAvailable(orderGetPosOrderLEntity))return;
                        int success = orderGetPosOrderLEntity.getSuccess();
                        if(success == 1) {
                            int PageCount = orderGetPosOrderLEntity.getPageCount();
                            page = orderGetPosOrderLEntity.getPageIndex();

                            List<OrderGetPosOrderLEntity.DataBean> data =
                                    orderGetPosOrderLEntity.getData();

                            if(data.size() > 0 && data.get(0).getList().size() > 0) {
                                rlNoData.setVisibility(View.GONE);
                                refreshLayout.setVisibility(View.VISIBLE);
                                if(page == 1) {
                                    if(orderRecordAdapter == null) {
                                        orderRecordAdapter =
                                                new OrderRecordAdapter(ScanOrderActivity.this, data.get(0).getList());
                                    } else {
                                        orderRecordAdapter.updateData(data.get(0).getList());
                                    }
                                } else {
                                    orderRecordAdapter.addData(data.get(0).getList());
                                }
                                recyclerview.setAdapter(orderRecordAdapter);
                            } else {
//                                ToastUtils.showToast(mContext, "没有数据了");
                                if(page == 1) {
                                    rlNoData.setVisibility(View.VISIBLE);
                                    refreshLayout.setVisibility(View.GONE);
                                }
                            }

                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(mContext, "autologin");
                            SharedPreferencesUtils.remove(mContext, "remberpassword");
                            startActivity(new Intent(mContext, BangGuidActivity.class));
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(orderGetPosOrderLEntity.getErrMsg());
                            SharedPreferencesUtils.remove(mContext, "autologin");
                            SharedPreferencesUtils.remove(mContext, "remberpassword");
                            startActivity(new Intent(mContext, LoginActivity.class));
                        } else {
                            ToastUtils.showToast(mContext,
                                    orderGetPosOrderLEntity.getErrMsg() + "");
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(mContext, "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(mContext, "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(mContext, "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @TargetApi(Build.VERSION_CODES.N)
    @OnClick({R.id.img_back, R.id.tv_date, R.id.tv_yesterday, R.id.tv_tomorrow,
            R.id.ll_wx, R.id.ll_zfb, R.id.ll_ysf, R.id.ll_digital})
    void clicked(View v) {
        switch(v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_date:
                showDatePick(tvDate.getText().toString());
                break;
            case R.id.tv_yesterday:
                tvDate.setText(subDay(tvDate.getText().toString()));
                if(tvDate.getText().toString().equals(sDateFormat.format(System.currentTimeMillis()))) {
                    tvTomorrow.setClickable(false);
                    tvTomorrow.setCompoundDrawables(null, null, ivArrowGrey, null);
                    tvTomorrow.setTextColor(getResources().getColor(R.color.font_value));
                } else {
                    tvTomorrow.setClickable(true);
                    tvTomorrow.setCompoundDrawables(null, null, ivArrowWhite, null);
                    tvTomorrow.setTextColor(getResources().getColor(R.color.white));
                }
                getDayData();
                getData(this, 1, paytype);
                break;
            case R.id.tv_tomorrow:
                tvDate.setText(addDay(tvDate.getText().toString()));
                if(tvDate.getText().toString().equals(sDateFormat.format(System.currentTimeMillis()))) {
                    tvTomorrow.setClickable(false);
                    tvTomorrow.setCompoundDrawables(null, null, ivArrowGrey, null);
                    tvTomorrow.setTextColor(getResources().getColor(R.color.font_value));
                } else {
                    tvTomorrow.setClickable(true);
                    tvTomorrow.setCompoundDrawables(null, null, ivArrowWhite, null);
                    tvTomorrow.setTextColor(getResources().getColor(R.color.white));
                }
                getDayData();
                getData(this, 1, paytype);
                break;
            case R.id.ll_wx:
                paytype = 1;
                tvWx.setTextColor(getResources().getColor(R.color.colorPrimary));
                tvWxMoney.setTextColor(getResources().getColor(R.color.colorPrimary));
                tvZfb.setTextColor(getResources().getColor(R.color.text_color3));
                tvZfbMoney.setTextColor(getResources().getColor(R.color.text_color3));
                tvYsf.setTextColor(getResources().getColor(R.color.text_color3));
                tvYsfMoney.setTextColor(getResources().getColor(R.color.text_color3));
                vWx.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                vZfb.setBackgroundColor(getResources().getColor(R.color.white));
                vYsf.setBackgroundColor(getResources().getColor(R.color.white));
                tvDigital.setTextColor(getResources().getColor(R.color.text_color3));
                tvDigitalMoney.setTextColor(getResources().getColor(R.color.text_color3));
                vDigital.setBackgroundColor(getResources().getColor(R.color.white));
                getData(this, 1, paytype);
                break;
            case R.id.ll_zfb:
                paytype = 2;
                tvWx.setTextColor(getResources().getColor(R.color.text_color3));
                tvWxMoney.setTextColor(getResources().getColor(R.color.text_color3));
                tvZfb.setTextColor(getResources().getColor(R.color.colorPrimary));
                tvZfbMoney.setTextColor(getResources().getColor(R.color.colorPrimary));
                tvYsf.setTextColor(getResources().getColor(R.color.text_color3));
                tvYsfMoney.setTextColor(getResources().getColor(R.color.text_color3));
                vWx.setBackgroundColor(getResources().getColor(R.color.white));
                vZfb.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                vYsf.setBackgroundColor(getResources().getColor(R.color.white));
                tvDigital.setTextColor(getResources().getColor(R.color.text_color3));
                tvDigitalMoney.setTextColor(getResources().getColor(R.color.text_color3));
                vDigital.setBackgroundColor(getResources().getColor(R.color.white));
                getData(this, 1, paytype);
                break;
            case R.id.ll_ysf:
                paytype = 7;
                tvWx.setTextColor(getResources().getColor(R.color.text_color3));
                tvWxMoney.setTextColor(getResources().getColor(R.color.text_color3));
                tvZfb.setTextColor(getResources().getColor(R.color.text_color3));
                tvZfbMoney.setTextColor(getResources().getColor(R.color.text_color3));
                tvYsf.setTextColor(getResources().getColor(R.color.colorPrimary));
                tvYsfMoney.setTextColor(getResources().getColor(R.color.colorPrimary));
                vWx.setBackgroundColor(getResources().getColor(R.color.white));
                vZfb.setBackgroundColor(getResources().getColor(R.color.white));
                vYsf.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

                tvDigital.setTextColor(getResources().getColor(R.color.text_color3));
                tvDigitalMoney.setTextColor(getResources().getColor(R.color.text_color3));
                vDigital.setBackgroundColor(getResources().getColor(R.color.white));
                getData(this, 1, paytype);
                break;

            case R.id.ll_digital:
                paytype = 8;
                tvWx.setTextColor(getResources().getColor(R.color.text_color3));
                tvWxMoney.setTextColor(getResources().getColor(R.color.text_color3));
                tvZfb.setTextColor(getResources().getColor(R.color.text_color3));
                tvZfbMoney.setTextColor(getResources().getColor(R.color.text_color3));
                tvYsf.setTextColor(getResources().getColor(R.color.text_color3));
                tvYsfMoney.setTextColor(getResources().getColor(R.color.text_color3));
                vWx.setBackgroundColor(getResources().getColor(R.color.white));
                vZfb.setBackgroundColor(getResources().getColor(R.color.white));
                vYsf.setBackgroundColor(getResources().getColor(R.color.white));

                tvDigital.setTextColor(getResources().getColor(R.color.colorPrimary));
                tvDigitalMoney.setTextColor(getResources().getColor(R.color.colorPrimary));
                vDigital.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                getData(this, 1, paytype);
                break;
        }
    }

    public String addDay(String currentDay) {

        Date date = null;
        try {
            date = (new SimpleDateFormat("yyyy-MM-dd")).parse(currentDay);
        } catch(ParseException e) {
            e.printStackTrace();
        }

        Calendar cal = Calendar.getInstance();

        cal.setTime(date);

        cal.add(Calendar.DATE, 1);

        date = cal.getTime();

        return (new SimpleDateFormat("yyyy-MM-dd")).format(date);
    }

    public String subDay(String currentDay) {

        Date date = null;
        try {
            date = (new SimpleDateFormat("yyyy-MM-dd")).parse(currentDay);
        } catch(ParseException e) {
            e.printStackTrace();
        }

        Calendar cal = Calendar.getInstance();

        cal.setTime(date);

        cal.add(Calendar.DATE, -1);

        date = cal.getTime();

        return (new SimpleDateFormat("yyyy-MM-dd")).format(date);
    }

}
